<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme
import resize from "@/views/dashboard/mixins/resize.js";

export default {
  mixins: [resize],
  props: {
    title: {
      type: Object,
      default: {},
    },
    showLeg: {
      type: Boolean,
      default: false,
    },
    toolbox: {
      type: Object,
      default: {},
    },
    data: {
      type: Array,
      default: () => [],
    },
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "350px",
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  computed: {
    nameList() {
      let arr = [];
      this.data.forEach((item) => {
        arr.push(item.name);
      });
      return arr;
    },
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, "macarons");
      this.chart.setOption({
        title: this.title,
        toolbox: this.toolbox,
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)",
        },
        legend: {
          show: this.showLeg,
          orient: "vertical",
          left: "38%",
          data: this.nameList,
        },
        series: [
          {
            // name: '访问来源',
            type: "pie",
            radius: "55%",
            center: ["50%", "60%"],
            data: this.data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      });
    },
  },
};
</script>
